import localStorage from '@/utils/localStorage'
import _config from '@/common/config'
const res = localStorage.getItem('userInfo')

var emptyUserInfo = {
  Name: '',
  Gid: '',
  Wid: '',
  Roles: [],
  Token: '',
  LastRefreshTime: '',
  Phone: '',
}

const _userInfo = res ? JSON.parse(res) : emptyUserInfo
const saveState = function () {
  localStorage.setItem('userInfo', JSON.stringify(state))
}
const state = {
  Phone: _userInfo['Phone'] || '',
  Token: _userInfo['Token'] || '',
  Name: _userInfo['Name'] || '',
  Wid: _userInfo['Wid'] || '',
  Roles: _userInfo['Roles'] || '',
  LastRefreshTime: _userInfo['LastRefreshTime'] || '',
  Gid: _userInfo['Gid'] || '',
}

const mutations = {
  setName: (state, data) => {
    state.Name = data
    saveState()
  },
  setWid: (state, data) => {
    state.Wid = data
    saveState()
  },

  setToken: (state, data) => {
    state.Token = data['Token']
    state.Phone = data['Phone']
    state.Name = data['Name']
    state.Wid = data['Wid']
    state.Gid = data['Gid']
    state.Roles = data['Roles']
    state.LastRefreshTime = uni.$u.date(new Date(), 'yyyy-mm-dd hh:MM:ss')
    saveState()
  },
}

const actions = {
  setName({ commit }, data) {
    commit('setName', data)
  },

  logOut({ commit }) {
    commit('setToken', emptyUserInfo)
  },
  setWid({ commit }, data) {
    commit('setWid', data)
    return Promise.resolve(data)
  },
  setToken({ commit }, data) {
    commit('setToken', data)
  },
  getToken({ commit }, _data) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${_config.baseUrl}/api/Open/Auth/GetToken`,
        data: _data,
        header: { redirectHost: _config.host },
        method: 'POST',
        success: function (res) {
          if (res.data.code == 0) {
            commit('setToken', res.data.data)
            console.log('======gettoken success')
            resolve('Login')
          } else if (res.data.code == -1) {
            console.log('======gettoken fail')
            resolve('NewUser')
          } else {
            console.log('======gettoken reset state')
            reject('未知错误')
          }
        },
        fail: function (err) {
          reject()
        },
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
